/*
 * @Description: 创建分组节点弹窗
 * @Author: Rfan
 * @Date: 2022-06-28 20:35:00
 * @LastEditTime: 2022-07-06 19:48:00
 */

import { FC, useEffect } from 'react';
import { Button, Form, Modal, Typography } from 'antd';
import { addTreeNodeById } from '@/utils';
import { addTreeNodeGroup, ITreeNodeGroupParams } from '@/api/floderTree';
import { useFolderTreeContext } from '@/components/FolderTree/contexts/FolderTreeContext';
import GroupForm from './common/GroupForm';
import type { ICommonDialog } from '@/interfaces/global';
import type { IFolderTreeNode } from '@/interfaces/folderTree';

interface CreateGroupNodeDialogProps extends ICommonDialog {
  node: IFolderTreeNode | null;
}

const CreateGroupNodeDialog: FC<CreateGroupNodeDialogProps> = (props) => {
  const { visible, node, onClose } = props;
  const { treeData, expandedKeys, setTreeData, setExpandedKeys } = useFolderTreeContext();
  const [form] = Form.useForm();

  useEffect(() => {
    if (visible) {
      //
    }
  }, [visible]);

  /**
   * @description: 关闭弹窗方法
   */
  const onCancel = () => {
    onClose();
  };

  /**
   * @description: 提交表单方法
   * @param {{ nodeName: string; remark: string }} vals 表单数据
   */
  const onFinish = (vals: { dirTreeRuleId: number }) => {
    if (node && node.id) {
      const params: ITreeNodeGroupParams = { ...vals, nodeId: node.id };
      addTreeNodeGroup(params).then((res) => {
        const { data } = res;
        console.log('add group success', data);
        data.map((item: any) => ({
          ...item,
          leafNode: true,
          isLeaf: true
        }));
        setTreeData(addTreeNodeById(treeData, data.pid, data));
        setExpandedKeys([...expandedKeys, data.pid]);
        onClose();
      });
    }
  };

  return (
    <Modal
      title="添加分组节点"
      visible={visible}
      width={400}
      destroyOnClose
      onCancel={onCancel}
      footer={[
        <Button key="close" onClick={onCancel}>
          关闭
        </Button>,
        <Button
          key="save"
          type="primary"
          onClick={() => {
            form.submit();
          }}
        >
          保存
        </Button>
      ]}
    >
      <Typography.Paragraph>选择已经配置好的分组方案，或创建新方案。</Typography.Paragraph>
      <Form form={form} preserve={false} onFinish={onFinish}>
        <GroupForm node={node} />
      </Form>
    </Modal>
  );
};

export default CreateGroupNodeDialog;
